/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.config.console;

import org.springframework.aop.scope.ScopedProxyUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;

import java.util.Properties;

/**
 * 控制台组件后置处理，获取组件启动参数
 *
 * @author ebert_chan
 */
public class ConsoleBeanPostProcessor implements DestructionAwareBeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        String targetBeanName = beanName;
        if (ScopedProxyUtils.isScopedTarget(targetBeanName)) {
            targetBeanName = ScopedProxyUtils.getOriginalBeanName(targetBeanName);
        }
        if (ConsoleManager.containsComponent(targetBeanName) && bean instanceof ConsoleBean) {
            ConsoleBean consoleBean = (ConsoleBean) bean;
            Properties properties = consoleBean.startupArguments();
            if (properties != null) {
                ConsoleManager.setProperties(targetBeanName, properties);
            }
        }
        return DestructionAwareBeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    @Override
    public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
        String targetBeanName = beanName;
        if (ScopedProxyUtils.isScopedTarget(targetBeanName)) {
            targetBeanName = ScopedProxyUtils.getOriginalBeanName(targetBeanName);
        }
        ConsoleManager.removeProperties(targetBeanName);
    }

}
